import React, {
  Component,
  useState,
  useEffect,
} from "react";
import {
  View,
  Text,
  TouchableHighlight,
  Image,
} from "react-native";
import Content from "../../components/content/content";
import styles from "./account-list-sheet";

import arrow from "../../asset/images/arrow-right.png";

import * as api from "../../api";

export default function AccountList(props) {
  const type = parseInt(props.navigation.state.params.type);

  const [data, setData] = useState([]);

  useEffect(() => {
    global.showLoading();
    api.getAccounts({
      platform: type,
    }).then(res => {
      setData(res.accounts);
    }).catch(rej => {
      global.showToast(rej);
    }).finally(() => {
      global.closeLoading();
    });
  }, []);

  addAccount = () => {
    props.navigation.navigate('AddAccount', {
      type,
      cb: (res) => {
        setData([...res, ...data]);
      }
    })
  }

  renderData = () => {
    return data.map((v, index) => {
      return (
        <TouchableHighlight key={index} underlayColor="#e6e6e6">
          <View style={styles.item}> 
            <View><Text ellipsizeMode="tail" style={{width:120}}>{v.account}</Text></View>
            <View style={{marginLeft:20}}><Text>{v.homepage_url}</Text></View>
          </View>
        </TouchableHighlight>
      )
    });
  }

  return (
    <Content>
			<View style={styles.content}>
        <TouchableHighlight underlayColor="#e6e6e6" onPress={addAccount}>
          <View style={[styles.item,{justifyContent: 'space-between',}]}>
            <View><Text>添加账号</Text></View>
            <View>
              <Image source={arrow} style={styles.icon}>
              </Image>
            </View>
          </View>
        </TouchableHighlight>
        {
          renderData()
        }
      </View>
		</Content>
  )
}